import configUrl from '@/util/url.js';
import { pathToBase64, base64ToPath } from '@/util/mmmm-image-tools/index.js';

/* #ifdef APP-PLUS */
/* #endif */

let rad = (d) => {
	return d * Math.PI / 180.0;
}

let getDistance = (lat1, lng1, lat2, lng2) => {
	let radLat1 = rad(lat1);
	let radLat2 = rad(lat2);
	let a = radLat1 - radLat2;
	let b = rad(lng1) - rad(lng2);
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));

	s = s * 6378.137; // EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000; //输出为公里

	let distance = s;
	let distance_str = "";

	if (parseInt(distance) >= 1) {
		distance_str = distance.toFixed(1) + "km";
	} else {
		distance_str = distance * 1000 + "m";
	}

	return s;
}

let deepClone = (target) => {
    // 定义一个变量
    let result;
    // 如果当前需要深拷贝的是一个对象的话
    if (typeof target === 'object') {
    // 如果是一个数组的话
        if (Array.isArray(target)) {
            result = []; // 将result赋值为一个数组，并且执行遍历
            for (let i in target) {
                // 递归克隆数组中的每一项
                result.push(deepClone(target[i]))
            }
         // 判断如果当前的值是null的话；直接赋值为null
        } else if(target===null) {
            result = null;
         // 判断如果当前的值是一个RegExp对象的话，直接赋值
        } else if(target.constructor===RegExp){
            result = target;
        }else {
         // 否则是普通对象，直接for in循环，递归赋值对象的所有值
            result = {};
            for (let i in target) {
                result[i] = deepClone(target[i]);
            }
        }
     // 如果不是对象的话，就是基本数据类型，那么直接赋值
    } else {
        result = target;
    }
     // 返回最终结果
    return result;
}

let cleanData = (target) => {
	let ret = {};

	Object.keys(target).forEach((key) => {
		if(target[key] !== '' && target[key] !== null) {
			ret[key] = target[key];
		}
	})

	return ret;
}


let formatDateStr = (str) => {
	let ret = '';

	let date = {
		y:{
			value: str.split(' ')[0].split('-')[0],
			text: '年'
		},
		M: {
			value: str.split(' ')[0].split('-')[1],
			text: '月'
		},
		d: {
			value: str.split(' ')[0].split('-')[2],
			text: '日'
		},
		h: {
			value: str.split(' ')[1].split(':')[0],
			text: '时'
		},
		m: {
			value: str.split(' ')[1].split(':')[1],
			text: '分'
		},
		s:{
			value: str.split(' ')[1].split(':')[2],
			text: '秒'
		}
	}

	for (let i in date) {
		date[i]['value'] = date[i]['value'].replace(/^[0]+/,'') || '0';
		ret += `${date[i]['value']}${date[i]['text']}`;
	}

	return ret;
}

let formatDateStr1 = (str, format = 'yyyy年MM月dd日') => {
	let ret = '';

	let date = {
		'y+': str.split(' ')[0].split('-')[0],
		'M+': (str.split(' ')[0].split('-')[1]),
		'd+': str.split(' ')[0].split('-')[2],
		'h+': str.split(' ')[1].split(':')[0],
		'm+': str.split(' ')[1].split(':')[1],
		's+': str.split(' ')[1].split(':')[2]
	}

	date['M+'] = (date['M+']).indexOf('0') == 0 ? parseInt(date['M+'].substring(1)) : parseInt(date['M+']);
	date['d+'] = (date['d+']).indexOf('0') == 0 ? parseInt(date['d+'].substring(1)) : parseInt(date['d+']);

	for (let i in date) {
		if(new RegExp('('+ i +')').test(format)) {
			format = format.replace(RegExp.$1, date[i])
		}
	}

	return format;
}

let isPtInPoly = (ALon, ALat, APoints) => {
	var iSum = 0,
		iCount;
	var dLon1, dLon2, dLat1, dLat2, dLon;
	if (APoints.length < 3) return false;
	iCount = APoints.length;

	for (var i = 0; i < iCount; i++) {
		if (i == iCount - 1) {
			dLon1 = APoints[i][0];
			dLat1 = APoints[i][1];
			dLon2 = APoints[0][0];
			dLat2 = APoints[0][1];
		} else {
			dLon1 = APoints[i][0];
			dLat1 = APoints[i][1];
			dLon2 = APoints[i + 1][0];
			dLat2 = APoints[i + 1][1];
		}
		//以下语句判断A点是否在边的两端点的水平平行线之间，在则可能有交点，开始判断交点是否在左射线上
		if (((ALat >= dLat1) && (ALat < dLat2)) || ((ALat >= dLat2) && (ALat < dLat1))) {
			if (Math.abs(dLat1 - dLat2) > 0) {
				//得到 A点向左射线与边的交点的x坐标：
				dLon = dLon1 - ((dLon1 - dLon2) * (dLat1 - ALat)) / (dLat1 - dLat2);
				if (dLon < ALon)
					iSum++;
			}
		}
	}

	if (iSum % 2 != 0)
		return true;
	return false;
}

let getUserInfo = () => {
	let userInfo = uni.getStorageSync('userInfo');
	let ret = ''

	if(userInfo){
		ret = userInfo;
	}

	return ret;
}

let mergeUrls = (url, obj) => {
	let ret = '';
	let arr = [];

	Object.keys(obj).forEach( item => {
		let str = `${item}=${obj[item]}`;

		arr.push(str);
	});

	let params = arr.join('&');

	ret = `${url}?${params}`;

	return ret;
}

let getBaseImages = (tempFilePaths) => {
	return new Promise(async (resolve, reject) => {
		let baseImages = []

		baseImages = tempFilePaths.map(async(tempFilePath) => {
			let path = await pathToBase64(tempFilePath);

			return path;
		})

		let res = await Promise.all(baseImages);

		resolve(res);
	})
}

let compressImage = (patch) => {
	return new Promise((resolve, reject) => {
		plus.zip.compressImage({
			src: patch,
			quality: 62,
			width: '50%',
			height: '50%',
			success: res => {
				resolve(res);
			},
			fail: res => {
				reject(res);
			}
		})
	})
}

let toLogin = () => {
	uni.reLaunch({
	    url: '/pages/login'
	});
}

let getRoutes = () => {
	let pages = getCurrentPages();
	let routes = pages.map((page) => page.route);

	return routes;
}

let getLocation = async () => {
	return await new Promise((resolve, reject) => {
		let obj = {
			type: 'gcj02',
			success: (res) => {
				resolve(res);
			},
			fail: (error) => {
				reject();
			}
		};

		uni.getLocation(obj);
	})
}

let moveToLocation = async (longitude, latitude, map) => {
	return await new Promise((resolve, reject) => {
		let obj = {
			longitude: longitude,
			latitude: latitude,
			success: () => {
				resolve();
			},
			fail: () => {
				reject();
			}
		}

		map.moveToLocation(obj);
	})
}


let chooseLocation = async (data) => {
	return await new Promise((resolve, reject) => {
		let obj = {
			success: () => {
				resolve();
			},
			fail: () => {
				reject();
			}
		}

		Object.assign(obj, data);

		uni.chooseLocation(obj);
	})
}

let getSystemInfo = async() => {
	return await new Promise((resolve, reject) => {
		uni.getSystemInfo({
			success: (res) => {
				resolve(res);
			}
		});
	});
}

let reverseGeocode= async (longitude, latitude) => {
	return await new Promise((resolve, reject) => {
		let pt = new plus.maps.Point( longitude, latitude );

		plus.maps.Map.reverseGeocode(
		pt,
		{},
		(event) => {
			let address = event.address; // 转换后的地理位置

			resolve({address: address});
		},
		(e) => {
			reject(e);
		});
	})
};

let chooseImage = async(data) => {
	return await new Promise((resolve, reject) => {
		let obj = {
			count: 1, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册选择
			success: (res) => {
			    resolve(res);
			},
			fail: () => {
				reject();
			}
		}

		Object.assign(obj, data);

		uni.chooseImage(obj);
	})
}

let previewImage = async(data) => {
	return await new Promise((resolve, reject) => {
		let obj = {}

		Object.assign(obj, data);

		uni.previewImage(obj);
	})
}


let getDictLabel = (value, arr, key, key2 = 'dict_label') => {
	let ret = '';
	let item = {};

	if (value !== undefined) {
		item = arr.find(item => item[key] == value);
		ret = item ? item[key2] : ''
	}

	return ret;
}

let getRegistrationID = async() => {
	return await new Promise((resolve, reject) => {

		let jpushModule = uni.requireNativePlugin("JG-JPush");
		jpushModule.getRegistrationID((res)=> {
			resolve(res);
		})
	})
}


/**
 * 将时间戳转换为指定格式的时间字符串
 * @param {Long} time  时间戳
 * @param {String} format 格式化，默认'yyyy-MM-dd HH:mm:ss'
 */
let timesFormat = (time, format = 'yyyy-MM-dd HH:mm:ss') => {
  if (!time || time <= 0) {
      return '';
  }
  let date = new Date(time);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;//月份是从0开始 , 所以+1
  let day = date.getDate();
  let hour = date.getHours();
  let min = date.getMinutes();
  let sec = date.getSeconds();
  let preArr = Array.apply(null, Array(10)).map((elem, index) => '0' + index);

  let dateStr = format.replace(/yyyy/g, year)
      .replace(/MM/g, preArr[month] || month)
      .replace(/dd/g, preArr[day] || day)
      .replace(/HH/g, preArr[hour] || hour)
      .replace(/mm/g, preArr[min] || min)
      .replace(/ss/g, preArr[sec] || sec);
  return dateStr;
}

let getMonDayAndSunDay = () => {
	let now = new Date();
	let nowTime = now.getTime() ;
	let day = now.getDay();
	let monDay = '';
	let sunDay = '';
	let oneDayTime = 24*60*60*1000 ;

	monDay = nowTime - (day - 1) * oneDayTime;

	sunDay = nowTime + (7 - day) * oneDayTime;

	return `${timesFormat(monDay, 'yyyy-MM-dd')}~${timesFormat(sunDay, 'yyyy-MM-dd')}`;
}

module.exports = {
	rad,
	getDistance,
	deepClone,
	cleanData,
	formatDateStr,
	formatDateStr1,
	isPtInPoly,
	getUserInfo,
	mergeUrls,
	getBaseImages,
	toLogin,
	getRoutes,
	compressImage,
	getLocation,
	moveToLocation,
	getSystemInfo,
	chooseLocation,
	reverseGeocode,
	chooseImage,
	previewImage,
	getDictLabel,
	getRegistrationID,
	timesFormat,
	getMonDayAndSunDay
}
